package com.noble.wawaji.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zego.wawaji.base.log.PToast;
import com.zego.wawaji.base.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.third.ThirdConstant;
import com.zego.wawaji.third.pay.PayConst;

/**
 * 微信支付回调页
 */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "WXPayEntryActivity";
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, ThirdConstant.WEIXIN_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:// 表示支付成功
                    PayConst.payFlag = true;
                    PToast.showShort("支付成功");
                    // 更新信息
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Update_MyInfo, null);
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:// 用户取消支付
                    PToast.showShort("支付取消");
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    PToast.showShort("支付被拒绝");
                    break;
                default:
                    PToast.showShort("支付出错");
                    break;
            }
            finish();
        } else {
            WXPayEntryActivity.this.finish();
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
